package com.lzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lzy.constant.Constants;
import com.lzy.context.LocalUser;
import com.lzy.dao.SysMenuDao;
import com.lzy.entity.SysRoleEntity;
import com.lzy.entity.SysRoleMenuEntity;
import com.lzy.exception.ServiceException;
import com.lzy.service.ISysRoleMenuService;
import com.lzy.service.ISysRoleService;
import com.lzy.utils.RedisCache;
import com.lzy.utils.StringUtil;
import com.lzy.utils.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.lzy.entity.SysMenuEntity;
import com.lzy.service.ISysMenuService;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysMenuService extends ServiceImpl<SysMenuDao, SysMenuEntity> implements ISysMenuService {

    @Autowired
    private SysMenuDao mapper;

    @Autowired
    private ISysRoleMenuService iSysRoleMenuService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public List<SysMenuEntity> selectPageList(Long id) {

        // 获取当前用户的所有角色id
        Set<String> roleKeys = LocalUser.getLoginUser().getRoles();
        if (StringUtil.isNull(roleKeys)) {
            throw new ServiceException("当前用户没有角色信息！");
        }
        Set<Long> roleIds = iSysRoleService
                .list(Wrappers
                        .<SysRoleEntity>lambdaQuery()
                        .in(SysRoleEntity::getRoleKey, roleKeys))
                .stream()
                .map(item -> item.getRoleId()).collect(Collectors.toSet());

        boolean isAdministrator = false;
        // 是否是超级管理员
        for (String roleKey : roleKeys) {
            if (roleKey.equalsIgnoreCase(Constants.ADMIN)) {
                isAdministrator = true;
                break;
            }
        }

        List<SysMenuEntity> records = null;

        if (isAdministrator) { // 超级管理员

            records = mapper.selectList(null);
        } else { // 其他用户

            Set<Long> menuIds = iSysRoleMenuService
                    .list(Wrappers
                            .<SysRoleMenuEntity>lambdaQuery()
                            .in(SysRoleMenuEntity::getRoleId, roleIds))
                    .stream()
                    .map(item -> item.getMenuId()).collect(Collectors.toSet());

            if (StringUtil.isNull(menuIds)) {
                throw new ServiceException("当前用户没有菜单信息！");
            }

            records = mapper
                    .selectPageList(new LambdaQueryWrapper<SysMenuEntity>()
                            .in(SysMenuEntity::getMenuId, menuIds));
        }

        return TreeUtil.screening(records);
    }
}